package com.yang.simple_rpc.common.protocol;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化消息协议实现类,将字节数组和对象通过流转换
 * @author : morikawaaaa
 * @date : 2022
 */

/**
 *     marshallingRequest     unmarshallingRequest
 * client编组请求------------------>server解组请求
 *
 *
 *
 *     unmarshallingReponse    marshallingResponse
 * client解组响应 <-----------------server编组响应
 */
public class SerializeMessageProtocol implements MessageProtocol{
    /**
     *抽取出来的序列化公共方法，将对象写到输出流上并保存在字节数组输出流中，并创建保存输出流的缓冲区
     * @param obj
     * @return 序列化的字节序列
     * @throws Exception
     */
    private byte[] serialize(Object obj) throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream ops = new ObjectOutputStream(baos);
        ops.writeObject(obj);
        return baos.toByteArray();
    }

    @Override
    public byte[] marshallingRequest(SimpleRequest req) throws Exception {
        return this.serialize(req);
    }

    /**
     *
     * @param bytes 反序列化将接收的字节数组经字节数组输入流到输入流，经readObject()方法读出并转化为请求消息对象实体
     * @return
     * @throws Exception
     */
    @Override
    public SimpleRequest unmarshallingRequest(byte[] bytes) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        return (SimpleRequest) ois.readObject();
    }

    @Override
    public byte[] marshallingResponse(SimpleResponse resp) throws Exception {
        return this.serialize(resp);
    }

    @Override
    public SimpleResponse unmarshallingReponse(byte[] bytes) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        return (SimpleResponse) ois.readObject();
    }
}
